//公共初始化模块
$(function() {
	main.run();
});

var main = {
	run : function() {
		this._init();
		this._start();
		this._init_events();
	},

	_init : function() {
		this.contextPath = $("#contextPath").val() || '';		
		this.$searchInput = $("#search_box > input.input_txt");
		this.$searchTips = $("#search_box > div.drop_down");
		this.ref = $.cookie("ref");		
	},

	_start : function() {				
		vd.start();
		
		this._layout_resize();
		var width = $(document.body).width();	
		if(width <= 800){
			main._play_close_side();
		}
		// search header
		searcher.init();	
		
		//ga.js
		wt_ga.start();
	
	},
	
	_init_events : function() {
		
		/*vc 下载专用*/
		if(main.ref){
			if (!vd.check()) {
				vd.keep();
			}
		}
		
		vh_sidebar._bind_events();		
		
		$(window).wresize(function() {
			main._layout_resize();
		});
		
		$("#close_side_btn").click(function() {			
			main._close_side();
		});

		$("#open_side_btn").click(function() {
			main._open_side();
		});

		$(window).load(function() {
			$("#midlle_div").mCustomScrollbar({
			/*
			 * scrollButtons:{ enable:true }
			 */
			// autoDraggerLength:true
			});
		});
		$("#footer_copy > span.change_ver").click(function(){
			$("#footer_copy > span.change_ver > ul").toggle();
		});
		$("#footer_copy > span.change_ver").mouseover(function(){
			$("#footer_copy > span.change_ver").css("cursor","pointer");
		});
	},

	_layout_resize : function() {	
		this._resize_search_input();
		this.fix_height_width();
		this.fix_footer_width();
	},
	
	_resize_search_input: function(){
		var width = $(document.body).width();		
		var searchInputWidth = this.$searchInput.width();
		var min = 140, max = 300, t1 = 338, t2 = 178,  sw = max, tw = t1;
		if(width <= 1000){
			sw = min;
			$('.fb_like').hide();
			$('#his_box').hide();
			$('#fr_box').hide();
			$('#m_info_column > div.m_view_column >  div.btn_box').removeClass("btn_box").addClass("btn_box2");
		}else{
			if(searchInputWidth < 140){
				sw = min;
			}else if(searchInputWidth >= 140 && searchInputWidth <= 300){
				var temp = width-948;				
				if(temp >= max){sw = max;}
				if(temp <= min){sw = min;}
			}else{
				sw = max;
			}
			$('#his_box').show();
			$('#fr_box').show();
			$('.fb_like').show();
			$('#m_info_column > div.m_view_column >  div.btn_box2').removeClass("btn_box2").addClass("btn_box");
		}
		
		if(sw == min){
			tw = t2;
		}
		
		this.$searchInput.css("width", sw);
		this.$searchTips.css("width", tw);
		
	},

	_close_side : function(){
		$("#side").animate({
			'left' : -180
		}, {
			duration : 200
		});
		var ww = ($(window).width());
		/*
		$("#main").animate({
			'margin-left' : '20',
			'width' : ww - 20
		}, {
			duration : 200
		});
		*/
		$("#main").css({"width":ww - 20,"margin-left":20});
		
	},
	
	_play_close_side : function() {
		$("#side").css("left",-180);
		var ww = $(window).width();
		//alert(ww);
		$("#main").css({"width":ww - 37,"margin-left":20});
	},

	_open_side : function() {
		/*
		$("#side").animate({
			left : 0
		}, 200);
		*/
		$("#side").css("left",0);
		var ww = $(window).width() - 180 ;
		$("#main").animate({
			'margin-left' : '180',
			'width' : ww
		}, 200);
		
	},

	fix_footer_width : function() {
		var boday = $(window).height();
		$("#side").height(boday - 75 + 30);
		if (parseInt(boday) < 600) {
			$("#footer").hide();
			$("#midlle_div").height($("#midlle_div").height() + 30);
		} else {
			$("#footer").slideDown("slow");
		}
	},

	fix_height_width : function() {
		$("#side_margin_div").remove();//先侧边栏撑得足够高，然后去掉，目的是防止大屏会闪动。
		var sideTop = $(".side_menu").height();
		var boday = $(window).height();
		$("#side").height(boday - 85);
		$("#midlle_div").height(boday - 85 - sideTop - 20);
		var leftsize = $("#side").css("left");
		var ww = 0;
		if(leftsize == "0px"){
			ww= ($(window).width() - 180);
		}else{
			ww= ($(window).width()- 20);
		}
		$("#main").width(ww);
	},

	addOrUpdateViewHistory : function(type, title, videoId) {
		if (!utils.isCookieEnabled()) {
			return;
		}
		// type = this._amend_type(type);		
		if (type) {
			var url = this.contextPath + "/view/history/update";
			var data = "type=" + type + "&title=" + encodeURIComponent(title);
			if (videoId) {
				data += "&videoId=" + videoId;
			}
			$.post(url, data, function(result) {
			});
		}
	},

	_amend_type : function(type) {
		if ('now-popular'.equalsIgnoreCase(type)) {
			return 'Movie';
		}
		if ('full-length'.equalsIgnoreCase(type)) {
			return 'Movie';
		}
		if ('this-year'.equalsIgnoreCase(type)) {
			return 'Movie';
		}
		if ('trailers'.equalsIgnoreCase(type)) {
			return 'Movie';
		}
		if ('browse'.equalsIgnoreCase(type)) {
			return 'Movie';
		}
		if ('TV'.equalsIgnoreCase(type)) {
			return 'Movie';
		}
		if ('mp3'.equalsIgnoreCase(type)) {
			return 'Music';
		}
		return false;
	}
};

var wt_ga = {
	start: function(){	
		if((typeof _gaq != 'undefined') && main.ref){
			if(main.ref){
				_gaq.push(['_trackPageview', document.location.pathname + '?f=' + main.ref]);
			}else{
				_gaq.push(['_trackPageview']);
			}			
		}
	}
};

var searcher = {
	searchType : 'video',
	oldDefault: 'Search for Videos...',
	defaultValue: 'Search for Videos...',
	defaultColor: '#DDDDDD',
	normalColor: '#666666',

	init : function() {
		this._check_i18n();
		
		$("#search_box").smenu({
			defaultValue : this.defaultValue,
			onchange : function(value) {
				searcher.handle_search_video(value);
			},
			selectedClass : 'curr'
		});
		/*

		$selectDiv.click(function() {
			$tipUL.toggle();
		});

		$tipUL.children("li").click(function() {
			var $this = $(this);
			var $span = $this.children("span").clone();
			searcher.searchType = $this.attr("st");
			$selectDiv.html($span);
			$tipUL.hide();
			var value = $input.val();
			var type = searcher.searchType;
			var s = "Videos";
			if(type == 'movie'){
				s = "Movies";
			}else if(type == 'music'){
				s = "Musics";
			}else if(type == 'tv'){
				s = "TV";
			}else if(type == 'anime'){
				s = 'Animes';
			}
			searcher.defaultValue = "Search for " + s + "...";
			
			if(value.startWith('Search for') || !value){				
				$input.val(searcher.defaultValue);
			}
		});		
		
		/*
		$input.click(function(){
			if($input.val() == searcher.defaultValue){
				$input.val("");
				$input.css({color: searcher.normalColor});
			}
		}).blur(function(){
			var val = $input.val();			
			if(val == searcher.oldDefault || ! val){				
				$input.val(searcher.defaultValue);
				$input.css({color: searcher.defaultColor});
			}
		});

		$("body").click(function(event) {
			if (event.target == $selectDiv[0]) {
				return;
			}
			if (event.target == $selectDiv.children("span")[0]) {
				return;
			}
			
			$tipUL.hide();
		});
		*/
	},
	
	_check_i18n: function(){
		var path = location.pathname;
		if(path.startWith(main.contextPath + "/world/")){
			this.isI18n = true;
		}
	},

	handle_search_video : function(query) {
		if(query == this.defaultValue || ! query){
			return;
		}				
		query = encodeURIComponent(query);
		if (query) {			
			var params = "search=" + query;
			if(this.isI18n){
				location.href = main.contextPath + "/world/results?" + params;
			}else{
				location.href = main.contextPath + "/results?" + params;
			}			
		}
	}
};

// vDownloader
var vd = {
	vid : 'wsytd',
	vkey : 'wsytd_key',

	start : function() {
		$("#down_vd_btn").click(function() {
			var url = "http://download.wondershare.com/video-converter-free_full1129.exe";
			_gaq.push([ '_trackEvent', 'vdownloader', 'Download', url ]);
			location.href = url;
		});

	},
	check : function() {
		if (document.getElementById(this.vid)) {
			return true;
		}
		if ($.cookie(this.vkey)) {
			return true;
		}
		return false;
	},
	keep : function() {
		$.cookie(this.vkey, 'true', {
			expires : 360 * 24 * 60 * 60
		});
	},
	go : function(url, title) {
		url = encodeURIComponent(url);
		title = encodeURIComponent(title);
		var wsytdd = "wsytd://" + url + "-WS-GUES-" + title;
		location.href = wsytdd;
	}
};

// view history sidebar
var vh_sidebar = {
	loaded : false,
	hiden : false,

	_bind_events : function() {
		vh_sidebar._display_history();
		vh_sidebar._display_hide_tag();
	},

	_display_history : function() {
		$("#his_box").click(function(event) {
			
			if (vh_sidebar.hiden) {
				$("#his_box > div.his_cont").hide();
				vh_sidebar.hiden = false;
			} else {
				$("#his_box > div.his_cont").show();
				vh_sidebar.hiden = true;
				vh_sidebar._list_view_history();
			}
			event.stopPropagation();
		});
	},

	_list_view_history : function() {
		var url = main.contextPath + "/view/history/list?t=" + new Date().getTime();
		$.get(url, function(result) {
			$("#his_box > div.his_cont").html(result);
			vh_sidebar._del_history();
			vh_sidebar._del_all_history();
			vh_sidebar._paging_display_history();
		});
	},
	_del_history : function() {		
		$("#his_box > div.his_cont > div.his_list > ul.list_ul > li > a.btn_del").click(function() {
			var $this = $(this);
			var id = $this.attr("vid");
			var url = main.contextPath + "/view/history/delete?id=" + id;
			$.post(url, function(result) {
				vh_sidebar._list_view_history();
			});
			$("#his_box > div.his_cont").show();
			return false;
		});
	},

	_del_all_history : function() {
		$("#his_box > div.his_cont > div.his_bottom > a").click(function() {
			var url = main.contextPath + "/view/history/delete?id=ALL";
			$.post(url, function(result) {
				vh_sidebar._list_view_history();
			});
			$("#his_box > div.his_cont").show();
			return false;
		});
	},

	_paging_display_history : function() {
		$("#his_box > div.his_cont > div.his_bottom > ul.his_menu > li").bind("click", function() {
			var page = $(this).text();
			$("#his_box > div.his_cont > div.his_list > ul.list_ul > li").hide();
			$("#his_box > div.his_cont > div.his_list > ul.list_ul > li.his" + (page - 1)).show();
			$("#his_box > div.his_cont > div.his_bottom > ul.his_menu > li").removeAttr("class");
			$(this).addClass("curr");
			$("#his_box > div.his_cont").show();
			return false;
		});
	},

	_display_hide_tag : function() {
		$("#his_box > div.his_cont > div.his_list > ul.list_ul > li").live("mouseover", function() {
			var $this = $(this);
			$this.children("a.btn_del").css("display", "block");
		});

		$("#his_box > div.his_cont > div.his_list > ul.list_ul > li").live("mouseout", function() {
			var $this = $(this);
			$this.children("a.btn_del").css("display", "none");
		});

		$("body").click(function(event) {
			if (vh_sidebar.hiden) {
				$("#his_box > div.his_cont").hide();
				vh_sidebar.hiden = false;
			}
		});
	}
};

var side_pub = {
	_init_side_genre_decade : function(obj) {
		var loc = location.href;
		var index = loc.indexOf("#");
		if (index >= 0) {
			this.params = loc.substring(index + 1);
		}
		if (this.params) {
			var paramArray = [];
			paramArray = this.params.split("&");
			for ( var i = 0; i < paramArray.length; i++) {
				if (paramArray[i].indexOf("genre") >= 0) {
					var $all = $("#genre_div > div.vscroll-content > ul > li > a");
					var mostIndex = 0;					
					var value = paramArray[i].substring(paramArray[i].indexOf("=") + 1);					
					$all.removeAttr("class");
					$all.each(function(index) {
						var $this = $(this);							
						if($this.attr("genre") == value){							
							obj.genre = value;
							mostIndex = index;
							return false;
						}
					});
					
					$all.eq(mostIndex).addClass("selected");
					
				} else if (paramArray[i].indexOf("decade") >= 0) {
					var $all = $("#decade_div > ul > li > a");
					var mostIndex = 0;
					var value = paramArray[i].substring(paramArray[i].indexOf("=") + 1);
					$all.removeAttr("class");
					$all.each(function(index) {
						var $this = $(this);
						var s = value + "s";
						if($this.text() == s){
							mostIndex = index;
							obj.decade = value;
							return false;
						}
					});
					
					$all.eq(mostIndex).addClass("selected");
					
				} else if (paramArray[i].indexOf("period") >= 0) {
					var value = paramArray[i].substring(paramArray[i].indexOf("=") + 1);
					$("#side_category_div > ul > li > a").removeAttr("class");
					$("#side_category_div > ul > li > a").each(function() {
						if ($(this).attr("popular") == decodeURI(value)) {
							$(this).addClass("selected");
							obj.popular = decodeURI(value);
						}
					});
				} else if (paramArray[i].indexOf("sort") >= 0) {
					var value = paramArray[i].substring(paramArray[i].indexOf("=") + 1);
					if (this.params.indexOf("initial") >= 0) {
						continue;
					} else {
						$("#alpha_div > a").removeClass("selected");
						$("#alpha_div > a").each(function() {
							if ($(this).text().toLowerCase() == decodeURI(value).toLowerCase()) {
								$(this).addClass("selected");
							}
						});
					}
				} else if (paramArray[i].indexOf("initial") >= 0) {
					var value = paramArray[i].substring(paramArray[i].indexOf("=") + 1);
					$("#alpha_div > a").removeClass("selected");
					$("#alpha_div > a").each(function() {
						if ($(this).text() == decodeURI(value)) {
							$(this).addClass("selected");
						}
					});
				}
			}
		}
	}
};